package com.example.yang.yixin.Activity;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.blankj.utilcode.util.FragmentUtils;
import com.example.yang.yixin.R;
import com.example.yang.yixin.Views.InputView;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;

public class RegisterActivity extends BaseActivity{
private InputView input_number,input_password,input_password_confirm;
    private String responseMsg = "";
    private static final int REQUEST_TIMEOUT = 5*1000;
    private static final int SO_TIMEOUT = 10*1000;
    private ImageView mIv_back;
  ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        input_number=findViewById(R.id.input_number);
        input_password=findViewById(R.id.input_password);

        input_password_confirm=findViewById(R.id.input_password_comfirmm);
        mIv_back=findViewById(R.id.iv_back);
        mIv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        init();
    }
    private void init(){
        initNarvBar(true,"注册",false);
    }

    public void OnRegisterbtnClick(View v){
        Thread registerThread = new Thread(new RegisterThread());
        registerThread.start();
    }
    private boolean Server(String username, String password,String urlStr)
    {
        boolean loginValidate = false;
        //使用apache HTTP客户端实现
        HttpPost request = new HttpPost(urlStr);
        //如果传递参数多的话，可以对传递的参数进行封装
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        //添加用户名和密码
        params.add(new BasicNameValuePair("username",username));
        params.add(new BasicNameValuePair("password",password));
        try
        {
            //设置请求参数项
            request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            HttpClient client = getHttpClient();
            //执行请求返回相应
            HttpResponse response = client.execute(request);

            //判断是否请求成功
            if(response.getStatusLine().getStatusCode()==200)
            {
                loginValidate = true;
                //获得响应信息
                responseMsg = EntityUtils.toString(response.getEntity());
            }
        }catch(Exception e)
        {
            e.printStackTrace();
        }
        return loginValidate;
    }
    public HttpClient getHttpClient()
    {
        BasicHttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
        HttpClient client = new DefaultHttpClient(httpParams);
        return client;
    }


    Handler handler = new Handler()
    {
        public void handleMessage(Message msg)
        {
          final   String username = input_number.getInputStr();
            switch(msg.what)
            {
                case 0:
                    Snackbar.make(getWindow().getDecorView(),"无网络连接！",Snackbar.LENGTH_LONG).setAction("检查网络", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {


                        }
                    }).show();
                    break;
                case 1:
                    Snackbar.make(getWindow().getDecorView(),"注册成功！",Snackbar.LENGTH_LONG).setAction("立即登录", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent=new Intent();
                            intent.putExtra("data",username);
                            intent.setClass(RegisterActivity.this,MainActivity.class);
                            startActivity(intent);

                        }
                    }).show();
                    break;
                case 2:
                    Snackbar.make(getWindow().getDecorView(),"用户名已存在！",Snackbar.LENGTH_LONG).setAction("重新输入", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            input_number.setText("");
                            input_password.setText("");
                            input_password_confirm.setText("");

                        }
                    }).show();
                    break;
                case  3:
                    Snackbar.make(getWindow().getDecorView(),"两次输入的密码不相同！",Snackbar.LENGTH_LONG).setAction("重新输入", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            input_number.setText("");
                            input_password.setText("");
                            input_password_confirm.setText("");
                        }
                    }).show();
                    break;
                case  4:
                    Snackbar.make(getWindow().getDecorView(),"任意一项都不能为空！",Snackbar.LENGTH_LONG).setAction("重新输入", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            input_number.setText("");
                            input_password.setText("");
                            input_password_confirm.setText("");
                        }
                    }).show();
                    break;
            }

        }
    };
    class RegisterThread implements Runnable {
        @Override
        public void run() {
            String username = input_number.getInputStr();
            String password = input_password.getInputStr();
            String repassword = input_password_confirm.getInputStr();
            Message msg = handler.obtainMessage();
            if (!password .equals(repassword)) {
                msg.what = 3;
                handler.sendMessage(msg);
            }
            else if(password.equals("")||repassword.equals("")||username.equals("")){
                msg.what=4;
                handler.sendMessage(msg);
            }
            else {
                boolean loginValidate = Server(username, password, "http://47.106.141.161/MyFirstAndroidApp/RegisterServlet");
                if (loginValidate) {
                    if (!responseMsg.equals("false")) {

                        msg.what = 1;
                        handler.sendMessage(msg);

                    }

                    if (responseMsg.equals("false")) {
                        msg.what = 2;
                        handler.sendMessage(msg);
                    }
                } else {
                    msg.what= 0;
                    handler.sendMessage(msg);
                }
            }
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }
}
